package com.heima.wemedia.gateway.filter;

import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 10161
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //gateway全局拦截器的书写，一般步骤为：
        /*
         * 1.先从exchange中获取 request 和 response 对象 还有被拦截的访问路径
         * 2. 判断被拦截的请求路径是否在放行名单中，如果是直接放行 return chain.filter(exchange)
         * 3.若不在放行名单，则判断在request中是否能获取到token
         * 4.检验token是否过期，过期了则拦截 response.setStatusCode设置响应码
         *   return response.setComplete() 直接相应回去
         *  5.token没过期，则直接放行。
         * */

        //1.获取request和response 以及被拦截的请求路径
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        //2.判断请求路径是否在放行名单（这里放行的我只设有login，所以不用数组存了）
        if (path.contains("/login")) {
            //在放行名单中，直接放行
            return chain.filter(exchange);
        }
        //3.从request中获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //token为空，则拦下
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.验证token是否过期 可能会有异常，tryCatch一下
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //是否是过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //并且解析token得出当前用户的id，存入请求的header中
            Object userId = claimsBody.get("id");

            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();

            //重置请求
            exchange.mutate().request(serverHttpRequest);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.token没过期，放行

        return chain.filter(exchange);
    }
    /*@Override
    public int getOrder(){
        return 0;
    }*/
}
